package com.freewater.javabase.demo.network.tcp;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 6666);
        try (final InputStream inputStream = socket.getInputStream()) {
            try (final OutputStream outputStream = socket.getOutputStream()) {
                handle(inputStream, outputStream);
            }
        }
        socket.close();
        System.out.println("disconnected...");
    }

    public static void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(System.in);
        System.out.println("[server]" + reader.readLine());
        while (true) {
            System.out.print(">>>> ");
            final String line = scanner.nextLine();
            writer.write(line);
            writer.newLine();
            writer.flush();
            final String resp = reader.readLine();
            System.out.println("<<<< " + resp);
            if ("bye".equals(resp)) {
                break;
            }
        }
    }
}
